package com.cjl.net.nio;

import com.cjl.designpattern.memento.actualcombat.Sys;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOClient {
    public static final String HOST = "127.0.0.1";
    public static final int PORT = 10001;

    public static void main(String[] args) {

    }

    static class NIOClientHandler implements Runnable{
        private SocketChannel socketChannel;
        private Selector selector;


        public NIOClientHandler() {
            try {
                socketChannel = SocketChannel.open();
                selector = Selector.open();
                socketChannel.configureBlocking(false);
            }catch (IOException e){
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            try {
                doConnect();
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            SelectionKey selectionKey = null;
            try {
                while (iterator != null && iterator.hasNext()) {
                    selectionKey = iterator.next();
                    iterator.remove();
                    if (selectionKey.isConnectable()) {
                        if (socketChannel.finishConnect()){
                            socketChannel.register(selector, SelectionKey.OP_READ);
                        }else {
                            System.exit(1);
                        }

                    }
                    if (selectionKey.isReadable()) {
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        int readBytes = socketChannel.read(buffer);
                        if (readBytes > 0){
                            buffer.flip();
                            byte[] bytes = new byte[buffer.remaining()];
                            buffer.get(bytes);
                            System.out.println("NIOClientHandler.run getMSg From server:"+new String(bytes,"UTF-8"));
                        }else if (readBytes < 0){
                            selectionKey.cancel();
                            socketChannel.close();
                        }

                    }
                }
            }catch (Exception e){

            }
        }

        private void doConnect() throws IOException {
            if (socketChannel.connect(new InetSocketAddress(HOST,PORT))){//链接成功
                socketChannel.register(selector, SelectionKey.OP_READ);
            }else {
                socketChannel.register(selector, SelectionKey.OP_CONNECT);
            }
        }
    }
}
